package com.eqdd.yiqidian.ui.gongneng.renshi.qiyewenhua;

import android.content.Intent;
import android.databinding.DataBindingUtil;

import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.QiyeImgActivityCustom;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.QiyeImgBean;
import com.eqdd.yiqidian.http.DialogCallBack;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.utils.ImageUtil;
import com.eqdd.yiqidian.utils.ItemTouchUtil;
import com.eqdd.yiqidian.utils.PicUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.eqdd.yiqidian.web.WebActivity;
import com.jakewharton.rxbinding.view.RxView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.schedulers.Schedulers;

public class QiyeImgActivity extends BaseActivity {
    private QiyeImgActivityCustom dataBinding;
    private SlimAdapterEx<QiyeImgBean> slimAdapterEx;
    private int num = 8;
    private int baseSort = 0;

    @Override
    public void initBinding() {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_qiye_img);
        initTopTitleBar(View.VISIBLE, "企业宣传");
    }

    @Override
    public void initData() {
        dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.recyclerView.setNestedScrollingEnabled(false);
        slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_60, new SlimInjector<QiyeImgBean>() {
            @Override
            public void onInject(QiyeImgBean data, IViewInjector injector) {
                injector.image(R.id.iv_img, data.getImageUrl())
                        .enable(R.id.bt_preview, !TextUtils.isEmpty(data.getUrl()))
                        .clicked(R.id.bt_delete, v -> {
                            deleteImg(data);
                        })
                        .clicked(R.id.bt_edit, v -> {

                            Bundle bundle = new Bundle();
                            bundle.putSerializable("bean", data);
                            startActivityForResult(EditImgActivity.class, bundle, Config.EDIT_IMG);
                        })
                        .clicked(R.id.bt_preview, v -> {
                            Bundle bundle = new Bundle();
                            bundle.putString(Config.TITLE, data.getTitle());
                            bundle.putString(Config.URL, data.getUrl());
                            startActivity(WebActivity.class, bundle);
                        });
            }
        }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
        ItemTouchUtil.openMove(dataBinding.recyclerView, new ItemTouchUtil.OnMove() {
            @Override
            public void move(int fromPos, int toPos) {
                slimAdapterEx.getData().get(fromPos).setSort(slimAdapterEx.getData().get(toPos).getSort() + slimAdapterEx.getData().get(fromPos).getSort());
                slimAdapterEx.getData().get(toPos).setSort(slimAdapterEx.getData().get(fromPos).getSort() - slimAdapterEx.getData().get(toPos).getSort());
                slimAdapterEx.getData().get(fromPos).setSort(slimAdapterEx.getData().get(fromPos).getSort() - slimAdapterEx.getData().get(toPos).getSort());
                Collections.swap(slimAdapterEx.getData(), fromPos, toPos);
                slimAdapterEx.notifyItemMoved(fromPos, toPos);
            }

            @Override
            public void release(int originFromPos, int fromPos, int toPos) {
                movePos(originFromPos, toPos);
            }
        });
    }

    private void movePos(int fromPos, int toPos) {
        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.QIYE_IMG_MOVE)
                .params("userGuid", user.getGuid())
                .params("companyId", user.getCompanyId())
                .params("para", dealPos(fromPos, toPos))
                .execute(new DialogCallBack<HttpResult>(QiyeImgActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {

                        }
                    }
                });
    }

    private String dealPos(int fromPos, int toPos) {
        if (fromPos > toPos) {
            fromPos = fromPos + toPos;
            toPos = fromPos - toPos;
            fromPos = fromPos - toPos;
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = fromPos; i <= toPos; i++) {
            stringBuilder.append(slimAdapterEx.getData().get(i).getId() + ":" + slimAdapterEx.getData().get(i).getSort() + ";");
        }
        System.out.println(stringBuilder.toString());
        return stringBuilder.substring(0, stringBuilder.length() - 1);
    }

    private void deleteImg(QiyeImgBean data) {
        OkGo.<HttpResult>post(HttpConfig.BASE_URL + HttpConfig.QIYE_IMG_DELETE)
                .params("userGuid", user.getGuid())
                .params("imageId", data.getId())
                .params("companyId", user.getCompanyId())
                .execute(new DialogCallBack<HttpResult>(QiyeImgActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult> response) {
                        HttpResult httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            int pos = slimAdapterEx.getData().indexOf(data);
                            slimAdapterEx.getData().remove(pos);
                            slimAdapterEx.notifyItemRemoved(pos);
                            dataBinding.includeAdd.getRoot().setVisibility(View.VISIBLE);
                        }
                    }
                });
    }

    @Override
    public void setView() {
        ImageUtil.setImage(R.mipmap.add, dataBinding.includeAdd.ivImg);
        dataBinding.includeAdd.lrBt.setVisibility(View.GONE);
        RxView.clicks(dataBinding.includeAdd.ivImg)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(v -> {
                    PicUtil.cut(QiyeImgActivity.this, 1000, 500, num);
                });
        refresh();
    }

    private void refresh() {
        OkGo.<HttpResult<List<QiyeImgBean>>>post(HttpConfig.BASE_URL + HttpConfig.QIYE_IMG_LIST)
                .params("companyId", user.getCompanyId())
                .execute(new DialogCallBack<HttpResult<List<QiyeImgBean>>>(QiyeImgActivity.this) {
                    @Override
                    public void onSuccess(Response<HttpResult<List<QiyeImgBean>>> response) {
                        HttpResult<List<QiyeImgBean>> httpResult = response.body();
                        ToastUtil.showShort(httpResult.getMsg());
                        if (httpResult.getStatus() == 200) {
                            if (httpResult.getItems().size() == 1 && httpResult.getItems().get(0).getCompanyId() == 0) {
                                baseSort = 0;
                                num = 8;
                                dataBinding.includeAdd.getRoot().setVisibility(View.VISIBLE);
                                return;
                            }
                            slimAdapterEx.updateData(httpResult.getItems());
                            if (slimAdapterEx.getData().size() >= 8) {
                                dataBinding.includeAdd.getRoot().setVisibility(View.GONE);
                            } else {
                                dataBinding.includeAdd.getRoot().setVisibility(View.VISIBLE);

                            }
                            num = 8 - httpResult.getItems().size();
                            baseSort = httpResult.getItems().get(httpResult.getItems().size() - 1).getSort();
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
            showLoading();
            Schedulers.newThread().scheduleDirect(() -> {
                for (int i = 0; i < localMedia.size(); i++) {
                    addImg(localMedia.get(i).getCompressPath(), i + 1 + baseSort);
                }
                refresh();
            });
        } else if (resultCode == Config.SUCCESS) {
            refresh();
        }
    }

    private void addImg(String compressPath, int pos) {
        try {
            okhttp3.Response response = OkGo.post(HttpConfig.BASE_URL + HttpConfig.QIYE_IMG_ADD)
                    .params("userGuid", user.getGuid())
                    .params("companyId", user.getCompanyId())
                    .params("file", new File(compressPath))
                    .params("url", "")
                    .params("title", "")
                    .params("sort", pos)
                    .execute();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
